<template>
    <div>
        <div class="crumbs">
            <el-breadcrumb separator="/">
                <el-breadcrumb-item>
                    <i class="el-icon-lx-cascades"></i>
                    {{pageTitle}}
                </el-breadcrumb-item>
            </el-breadcrumb>
        </div>
        <acc-set-card></acc-set-card>
        <div class="container" :style="{'min-height': containerHeight + 'px'}">
            <vxe-toolbar>
                <template v-slot:buttons>
                    <el-button type="primary" icon="el-icon-folder-add" @click="goAdd">新增</el-button>
                    <!-- <el-button type="warning" icon="el-icon-edit" @click="goEdit">修改</el-button> -->
                    <el-button type="danger" icon="el-icon-delete" @click="delAllSelection">删除</el-button>
                </template>
            </vxe-toolbar>

            <div class="handler-box">
                <el-form label-width="100px" :rules="rules" :model="query" ref="searchRuleForm">
                    <el-row>
                        <el-col :sm="20" :md="6">
                            <el-form-item label="账套代码" prop="setBookId">
                                <el-input v-model="query.setBookId" clearable></el-input>
                            </el-form-item>
                        </el-col>

                        <el-col :sm="20" :md="6">
                            <el-form-item label="年度" prop="accYear">
                                <el-date-picker
                                    v-model="query.accYear"
                                    type="year"
                                    value-format="yyyy"
                                    placeholder="选择年"
                                ></el-date-picker>
                            </el-form-item>
                        </el-col>

                        <el-col :sm="20" :md="6" align="center">
                            <el-button type="primary" icon="el-icon-search" @click="getData">搜索</el-button>
                            <el-button type="info" @click="resetForm('searchRuleForm')">重置</el-button>
                        </el-col>
                    </el-row>
                </el-form>
            </div>

            <vxe-table
                border
                resizable
                keep-source
                highlight-hover-row
                highlight-hover-column
                ref="xTree"
                row-id="id"
                height="500"
                :loading="loading"
                :data="tableData"
            >
                <!-- <vxe-table-column type="radio" title width="60"></vxe-table-column> -->
                <vxe-table-column type="seq" width="60"></vxe-table-column>
                <vxe-table-column field="setBookId" title="账套代码"></vxe-table-column>
                <vxe-table-column field="accYear" title="年度"></vxe-table-column>
                <vxe-table-column field="accPeriod" title="期间"></vxe-table-column>
                <vxe-table-column field="accWeek" title="周次"></vxe-table-column>
                <vxe-table-column field="accQuarter" title="季度"></vxe-table-column>
                <vxe-table-column field="accDateStart" title="起始日期">
                    <template slot-scope="scope">{{scope.row.accDateStart|formatDate}}</template>
                </vxe-table-column>
                <vxe-table-column field="accDateEnd" title="截止日期">
                    <template slot-scope="scope">{{scope.row.accDateEnd|formatDate}}</template>
                </vxe-table-column>
            </vxe-table>

            <vxe-pager
                background
                auto-hidden
                size="small"
                :loading="loading"
                :current-page="pagination.pageIndex"
                :page-size="pagination.pageSize"
                :total="pagination.pageTotal"
                :layouts="['PrevPage', 'JumpNumber','NextPage', 'Total']"
                @page-change="handlePageChange"
            ></vxe-pager>
        </div>

        <el-dialog title="新增" :visible.sync="dialogVisible" width="30%" :before-close="handleClose">
            <el-form :model="ruleForm" :rules="rules" ref="ruleForm" label-width="120px">
                <el-form-item label="账套代码" prop="setBookId">
                    <el-input v-model="ruleForm.setBookId" clearable></el-input>
                </el-form-item>

                <el-form-item label="年度" prop="accYear">
                    <el-date-picker
                        v-model="ruleForm.accYear"
                        value-format="yyyy"
                        type="year"
                        placeholder="选择年"
                    ></el-date-picker>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="handleClose">取 消</el-button>
                <el-button type="primary" @click="submitForm('ruleForm')">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>


<script>
import appMain from '../../../utils/app_main';
import _ from 'lodash';
import XEUtils from 'xe-utils';

export default {
    data() {
        return {
            pageTitle: '',
            containerHeight: '',
            tableData: [
                {
                    accDateEnd: '1991-04-09T12:16:14.71Z', //截止日期
                    accDateStart: '1990-05-12T09:28:13.969Z', //起始日期
                    accPeriod: -39189871, //会计期别
                    accQuarter: -12409086, //会计季度
                    accWeek: -12779962, //周次
                    accYear: -15551679, //会计年度
                    periodId: 'officia nulla dolore', //主键
                    setBookId: 'aute minim in sint' //账套代码
                },
                {
                    accDateEnd: '1949-01-14T14:44:53.983Z',
                    accDateStart: '1993-12-10T16:40:37.878Z',
                    accPeriod: -36756502,
                    accQuarter: -19257170,
                    accWeek: -16150390,
                    accYear: 29182752,
                    periodId: 'veniam eli',
                    setBookId: 'deserunt ullamco fu'
                },
                {
                    accDateEnd: '1995-05-23T03:22:45.322Z',
                    accDateStart: '1948-06-02T03:33:50.639Z',
                    accPeriod: -45055630,
                    accQuarter: 75619245,
                    accWeek: 77456324,
                    accYear: 41363204,
                    periodId: 'nisi ea aute veniam',
                    setBookId: 'velit'
                },
                {
                    accDateEnd: '1992-06-05T06:32:44.967Z',
                    accDateStart: '1941-04-05T16:15:37.512Z',
                    accPeriod: 96957260,
                    accQuarter: 15407903,
                    accWeek: -45706297,
                    accYear: 60545751,
                    periodId: 'magna esse est aute',
                    setBookId: 'dolor consequat ut'
                },
                {
                    accDateEnd: '1997-07-31T09:00:18.837Z',
                    accDateStart: '1968-10-10T06:55:51.644Z',
                    accPeriod: 38501866,
                    accQuarter: 48923058,
                    accWeek: -24835521,
                    accYear: 96932988,
                    periodId: 'voluptate',
                    setBookId: 'veniam'
                }
            ],
            checkTableRow: {
                // categoryId: 'string', //科目类别
                // categoryName: 'string', //科目类别名字
                // children: [], //
                // companyId: 'string', //公司id
                // currFlag: 1, //是否核算外币：0:否 1是-
                // dealFlag: 1, //是否合算往来单位：0否，1是
                // deptFlag: 1, //是否核算部门:0否，1是
                // description: 'string', //科目名称
                // drFlag: 0, //余额方向 1.借方 2.贷方
                // empFlag: 0, //是否核算人员：0否，1是
                // id: 'string', //
                // level: 0, //科目层级：最上层总账科目1，下一层为2，独立科目99
                // parentSubId: 'string', //上级科目
                // proFlag: 0, //是否合算项目：0否，1是
                // prolossFlag: 1, //结转损益方向：1.自动转出（结算没有余额） 2.不转出（结算有余额）
                // subjectId: 'string', //科目代码
                // type: 0 //科目性质:1.总账科目,总账科目有下级科目 2.明细科目，最底层 3.独立科目没有上下级科目
            },
            loading: false,
            pagination: {
                pageIndex: 1,
                pageSize: 10,
                pageTotal: 0
            },
            query: {
                accYear: '', //会计年度
                setBookId: '' //账套代码
            },
            //会计期间
            periodList: [],
            rules: {
                setBookId: [
                    { required: true, message: '请输入账套代码', trigger: 'change' },
                    { min: 2, max: 50, message: '长度在 2 到 50 个字符', trigger: 'change' }
                ],
                accYear: [{ required: true, message: '请选择', trigger: 'change' }]
            },
            dialogVisible: false, //新增
            dialogVisibleEdit: false, //编辑科目
            ruleForm: {
                setBookId: '', //帐套编号
                year: '' //年份
            }, //新增model
            editForm: {}
        };
    },
    created() {
        this.getData();
    },
    mounted() {
        var div_height = window.screen.availHeight;
        var height = div_height - 100;
        this.containerHeight = height - 200;
        this.pageTitle = this.$router.currentRoute.meta.title;
        //$refs.xTree.setAllTreeExpand(true);
    },
    methods: {
        handlePageChange({ currentPage, pageSize }) {
            this.pagination.pageIndex = currentPage;
            this.pagination.pageSize = pageSize;
            this.getData();
        },

        //点击单选方法
        currentChangeEvent({ row }) {
            this.checkTableRow = row;
            console.log('currentChangeEvent', this.checkTableRow);
        },
        getData() {
            this.loading = true;
            console.log('getData', this.loading);
            let params = {
                pageNo: this.pagination.pageIndex,
                pageSize: this.pagination.pageSize,
                record: this.query
            };

            appMain
                .accPeriodFindAllPage(params)
                .then(res => {
                    if (res.data.code === 20000) {
                        //TODO 测试环境使用
                        this.timer = setTimeout(() => {
                            //设置延迟执行
                            this.tableData = res.data.data.list;
                            this.pagination.pageSize = res.data.data.pageSize;
                            this.pagination.pageIndex = res.data.data.pageNum;
                            this.pagination.pageTotal = res.data.data.total;
                            this.loading = false;
                        }, 300);

                        console.log('getData tableData', this.tableData);
                    } else {
                        this.loading = false;
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    this.loading = false;
                    console.log(err);
                });
        },
        goAdd() {
            //this.dialogVisible = true;
            this.$router.push({
                path: '/fiscalPeriodDetail' //跳转的路径
            });
        },
        goEdit() {
            //this.$XModal.alert(this.checkTableRow.id);
            //this.$XModal.alert(JSON.stringify(this.$refs.xTree.getRadioRecord()));
            if (this.$refs.xTree.getRadioRecord() != null) {
                this.editForm = _.clone(this.$refs.xTree.getRadioRecord());
                this.dialogVisibleEdit = true;
            } else {
                this.$message.info('请选择一条记录,再进行编辑');
            }
        },
        delAllSelection() {
            // if (this.$refs.xTree.getRadioRecord() != null) {
            //     this.editForm = _.clone(this.$refs.xTree.getRadioRecord());
            // } else {
            //     this.$message.info('请选择一条记录,再进行编辑');
            //     return;
            // }

            this.$refs['searchRuleForm'].validate(valid => {
                if (!valid) {
                    this.$message.info('请输入会计期间条件,再进行删除');
                    return;
                }

                // 二次确认删除
                this.$confirm('确定要删除吗？', '提示', {
                    type: 'warning'
                })
                    .then(() => {
                        //请求接口删除数据
                        this.deleteRate();
                    })
                    .catch(() => {});
            });
        },
        deleteRate() {
            appMain
                .accPeriodDel(this.query.setBookId, this.query.accYear)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.getData();
                        this.$message.success(res.data.message);
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },

        addRate() {
            appMain
                .accPeriodGenerate(this.ruleForm.setBookId, this.ruleForm.accYear)
                .then(res => {
                    if (res.data.code === 20000) {
                        this.dialogVisible = false;
                        this.getData();
                        this.$message.success(res.data.message);
                    } else {
                        this.$message.error(res.data.message);
                    }
                })
                .catch(err => {
                    console.log(err);
                });
        },

        handleClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                    this.dialogVisible = false;
                    done();
                })
                .catch(_ => {});
        },
        submitForm(formName) {
            this.$refs[formName].validate(valid => {
                if (valid) {
                    if (formName == 'searchRuleForm') {
                        //新增科目
                        this.getData();
                    } else if (formName == 'ruleForm') {
                        this.addRate();
                    } else if (formName == 'editForm') {
                        this.updateRate();
                    }
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        resetForm(formName) {
            this.$refs[formName].resetFields();
            this.pagination.pageIndex = 1;
        }
    },
    computed: {},
    watch: {
        dialogVisible(newValue, oldValue) {
            console.log('dialogVisible', newValue);
            if (newValue == false) {
                this.ruleForm = {
                    setBookId: '', //帐套编号
                    year: '' //年份
                };
                this.$refs['ruleForm'].resetFields();
                console.log('dialogVisible ruleForm', this.ruleForm);
            }
        }
    },
    filters: {
        //时间过滤器
        formatDate: function(val) {
            let date = new Date(val);
            return appMain.formatDate(date, 'yyyy-MM-dd hh:mm:ss');
        }
    }
};
</script>

<style lang="css" scoped>
.el-card {
    height: 100%;
}

.flex-right {
    padding: 20px;
}

.handler-box {
    border: 1px solid rgb(232, 234, 236);
    padding: 5px;
    margin-bottom: 15px;
}

.tree-box .flex-left {
    padding: 0px !important;
}

.el-input {
    max-width: 220px;
}
.el-date-editor{
   width: 100%!important;
}
</style>